package com.internetCafes.spms.common.module.mongodb;

import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Map;

/**
 * Created by Sunny on 2018/1/11.
 */
public class MongodbBaseService {

    public Query getQueryParams(Map<String, Object> params){
        Query query = new Query();

        if(!params.isEmpty()){
            Criteria criteria = null;
            String key = "";
            String sortStr = "";
            Object[] keys = params.keySet().toArray();

            if(keys.length > 1){
                key = (String)keys[0];
                if ("orderby".equals(key.toLowerCase())) {
                    sortStr = String.valueOf(params.get(key));
                } else {
                    criteria = Criteria.where(key).is(params.get(key));
                }

                for(int i= 1; i<keys.length; i++ ){
                    key = (String)keys[i];
                    if ("orderby".equals(key.toLowerCase())) {
                        sortStr = String.valueOf(params.get(key));
                        continue;
                    }

                    if(criteria == null){
                        criteria = Criteria.where(key).is(params.get(key));
                    } else {
                        criteria.and(key).is(params.get(key));
                    }
                }
            }else{
                key = (String)keys[0];
                criteria = Criteria.where(key).is(params.get(key));
            }
            query.addCriteria(criteria);

            ReflectionUtils.sort(query, sortStr);
        }

        return query;
    }
}
